
/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var fs = require('fs');
var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', function(req,res){
	var user={
		first_name:'robin',
		usrname:'jiang',
		address:'nanjing',
		friends:'100000000'
	};
	//index.jade 可简写为index
	res.render('index.jade',{title:'User',user:user});
});
app.get('/users', user.list);
app.get('/users/:id', function(req,res){
	var users={
		1:{first_name:'robin',
		usrname:'jiang',
		address:'nanjing',
		friends:'100000000'},
		2:{first_name:'aaa',
		usrname:'ccc',
		address:'nanjing',
		friends:'100000000'}
	};
	res.render('index.jade',{title:'User',user:users[req.params.id]});
	//res.send('user id is:'+req.params.id);
});
app.get('/about',function(req,res){
	res.send('Hello from the about router!');
});

app.post('/',function(req,res){
	res.send(req.body);
});

//将数据写入文件
app.get('/writeFile', function(req,res){
	var data = '这是测试数据>>>this is a demo.';
	fs.writeFile('tmp/file.txt',data,function(err){
		if(!err){
			console.log('Wrote data to file.txt');
			res.send('Wrote data to file.txt');			
		}else{
			console.log('Something wrong:'+err);	
			throw err;
		}
	});
});
//读取文件数据
app.get('/readFile', function(req,res){
	fs.readFile('tmp/file.txt','utf8',function(err,data){
		if(!err){
			res.send('Read data:'+data+'env:'+process.env.JAVA_HOME);
						
		}else{
			console.log('Something wrong:'+err);	
			throw err;
		}
	});
});

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
